<template>
  <div class="app-container">
    <el-form
      class="searchform"
      @submit.native.prevent
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="50px"
    >
      <el-row>
        <el-col :span="5">
          <el-form-item label="编码">
            <el-input
              v-model="queryParams.queryString"
              placeholder="请输入标准编码或名称"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="table-wrapper">
      <div class="tableoperation">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="openDialog()"
          >添加</el-button
        >
      </div>

      <el-table
        v-loading="loading"
        :data="inspectionStandardList"
        :height="height - 400 + 'px'"
        @row-dblclick="(row) => openDialog(row, '3')"
      >
        <el-table-column label="编码" align="center" prop="standardNumber" />
        <el-table-column label="标准名称" align="center">
          <template slot-scope="scope">
            <span @click="viewFile(scope.row.standardOssId)" class="viewfile">{{
              scope.row.standardName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="150">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.status_disable"
              :value="scope.row.state"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="140"
        />
        <el-table-column align="center" label="操作" width="300">
          <template slot-scope="{ row }">
            <el-button
              v-if="row.state == '1'"
              @click.native.prevent="handleUpdateState(row, '0')"
              type="text"
            >
              启用
            </el-button>
            <el-button
              v-if="row.state == '0'"
              @click.native.prevent="handleUpdateState(row, '1')"
              type="text"
              style="color: #f32d2d"
            >
              停用
            </el-button>
            <el-button @click.native.prevent="openDialog(row, '2')" type="text">
              编辑
            </el-button>
            <el-button
              v-if="row.state == '1'"
              @click.native.prevent="handleDelete(row)"
              type="text"
              style="color: #f32d2d"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="1100px"
      v-dialogDrag="true"
    >
      <el-form
        :model="form"
        :disabled="status == '3'"
        :rules="rules"
        ref="form"
        size="small"
        label-width="100px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="标准编码" prop="standardNumber">
              <el-input
                v-model="form.standardNumber"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标准名称" prop="standardName">
              <el-input
                v-model="form.standardName"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标准状态" prop="state">
              <el-select v-model="form.state" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.status_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标准附件" prop="standardOssId">
              <el-input v-model="form.standardOssId" v-if="false" />
              <el-upload
                ref="upload"
                :action="upload.url"
                :headers="upload.headers"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleFileSuccessSecond"
                :before-upload="beforeAvatarUpload"
                :file-list="fileList"
                accept=".pdf"
                multiple
              >
                <el-button
                  v-if="status != '3'"
                  icon="el-icon-upload"
                  size="mini"
                  plain
                  type="primary"
                  >上传文件</el-button
                >
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标准描述">
              <el-input
                type="textarea"
                rows="3"
                maxlength="100"
                show-word-limit
                v-model="form.remarks"
                :placeholder="status != '3' ? '请输入' : ''"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button type="primary" v-if="status != '3'" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  inspectionStandardList,
  inspectionStandardExport,
  inspectionStandardListing,
  inspectionStandardDetail,
  inspectionStandardAdd,
  inspectionStandardEdit,
  inspectionStandardDelete,
  updateState,
} from "@/api/basicData/inspectionStandard";
import { listOss, listByIds, delOss } from "@/api/system/oss";
import { getToken } from "@/utils/auth";

export default {
  name: "inspectionStandard",
  dicts: ["status_disable"],
  data() {
    return {
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单校验
      rules: {
        standardNumber: [
          { required: true, message: "标准编码不能为空", trigger: "blur" },
        ],
        standardName: [
          { required: true, message: "标准名称不能为空", trigger: "blur" },
        ],
        state: [
          { required: true, message: "标准状态不能为空", trigger: "blur" },
        ],
        standardOssId: [
          { required: true, message: "请上传附件", trigger: "change" },
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
          "Content-Disposition": "inline",
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/oss/upload",
      },
      // 视图高度
      height: document.documentElement.clientHeight,
      // 设备标准列表
      inspectionStandardList: [],
      activeName: "0",
      total: 0,
      deptOptions: [],
      dialogVisible: false,
      status: "",
      title: "",
      typeDialogVisible: false,
      typeform: {},
      // 设备类型列表
      inspectionTypeList: [],
      // 选择的检测类型
      inspectionTypeId: null,
      // 检测标准下拉框
      inspectionStandardSelect: [],
      // 上传的文件列表
      fileList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取标准列表
    getList() {
      this.loading = true;
      inspectionStandardList(this.queryParams).then((response) => {
        this.inspectionStandardList = response.rows || [];
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取类型列表
    getTypeList() {
      inspectionTypeList().then((response) => {
        this.inspectionTypeList = response.rows;
      });
    },
    // 打开对话框
    openDialog(row, status) {
      console.log("子row", row);
      this.resetForm("form");
      // this.getInspectionStandardListing(); /* 获取检测标准下拉框 */
      if (row) {
        this.status = status;
        this.title = this.status == "2" ? "编辑标准" : "查看标准";
        inspectionStandardDetail(row.standardId).then((response) => {
          this.form = response.data;
          this.form.state = this.form.state && this.form.state.toString();
          if (this.form.standardOssId) {
            listByIds(this.form.standardOssId).then((response) => {
              this.fileList = response.data;
              this.fileList.forEach((item) => {
                item.name = item.originalName;
              });
            });
          }
          console.log("this.fileList", this.fileList);
          this.dialogVisible = true;
        });
      } else {
        this.status = "1";
        this.title = "添加标准";
        this.form = {
          standardOssId: null,
          state: "0",
        };
        this.fileList = [];
        this.dialogVisible = true;
      }
    },
    // 打开类型对话框
    openTypeDialog() {
      this.typeDialogVisible = true;
    },
    // 提交按钮
    submitForm() {
      this.form.standardOssId = this.fileList
        .map((item) => {
          if (item.ossId) {
            return item.ossId; /* 回显的列表格式 */
          } else if (item.response.data) {
            return item.response.data.ossId; /* 新上传的列表格式 */
          }
        })
        .join(",");
      console.log("this.form.standardOssId", this.form.standardOssId);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.status == "1") {
            inspectionStandardAdd(this.form).then((response) => {
              this.$modal.msgSuccess("添加成功");
              this.dialogVisible = false;
              this.getList();
            });
          }
          if (this.status == "2") {
            inspectionStandardEdit(this.form).then((response) => {
              this.$modal.msgSuccess("编辑成功");
              this.dialogVisible = false;
              this.getList();
            });
          }
        }
      });
    },
    // 更新状态
    handleUpdateState(row, state) {
      this.$modal
        .confirm(
          `是否确认${state === "1" ? "停用" : "启用"}标准 [${
            row.standardName
          }]？`
        )
        .then(() => {
          this.loading = true;
          return updateState(row.standardId, state);
        })
        .then(() => {
          this.$modal.msgSuccess(`${state === "1" ? "停用" : "启用"}成功`);
          this.getList();
        })
        .finally(() => {});
    },
    // 删除
    handleDelete(row) {
      this.$modal
        .confirm(
          `是否确认删除编码${row.standardNumber}的标准[${row.standardName}]？`
        )
        .then(() => {
          this.loading = true;
          return inspectionStandardDelete(row.standardId);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryParams");
      this.getList();
    },
    // 文件移除
    handleRemove(file, fileList) {
      console.log("handleRemove", fileList);
      this.fileList = fileList;
    },
    // 列表文件预览
    viewFile(ossId) {
      if (ossId) {
        listByIds(ossId).then((response) => {
          window.open(response.data[0].url, "PDF", "");
        });
      } else {
        this.$modal.msgWarning("暂无文件");
      }
    },
    // 弹框文件预览
    handlePreview(file, fileList) {
      console.log("handlePreview", file, fileList);
      // 上传时
      if (file.response && file.response.data) {
        window.open(file.response.data.url, "PDF", "");
      } else if (file.url) {
        window.open(file.url, "PDF", "");
      }
    },
    beforeRemove(file, fileList) {
      console.log("beforeRemove", fileList);
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 文件上传成功处理
    handleFileSuccessSecond(response, file, fileList) {
      console.log("response, file, fileList", response, file, fileList);
      if (response.code == 500) {
        this.$modal.msgWarning(response.msg);
      }
      this.fileList = fileList;
      this.upload.open = false;
      this.upload.isUploading = false;
    },
    // 上传前
    beforeAvatarUpload(file) {
      console.log("file", file);
      let isPDF = file.type === "application/pdf";
      if (!isPDF) {
        this.$message.warning("仅支持pdf格式，请重新上传!");
      }
      return isPDF;
    },
  },
};
</script>

<style lang="scss" scoped>
.title {
  padding-left: 10px;
  border-left: 5px solid #2a72ee;
  text-align: left;
  font-weight: bolder;
  font-size: 16px;
  margin-bottom: 30px;
  button {
    margin-left: 10px;
  }
}
.box {
  border: 2px solid #559bff;
  min-height: 100px;
  margin-top: -10px;
  margin-bottom: 20px;
  padding: 10px;
  .item {
    padding: 5px;
    border: 1px solid #999;
    border-radius: 3px;
    display: inline-block;
    margin-right: 10px;
    cursor: pointer;
    &:hover {
      color: #2a72ee;
      border-color: #2a72ee;
    }
    &.selected {
      background-color: #2a72ee;
      color: #fff;
      border-color: #2a72ee;
    }
  }
}
.operation {
  margin-block: 30px;
}
::v-deep .el-textarea__inner {
  resize: none;
}
.viewfile {
  color: #2a72ee;
  cursor: pointer;
  margin-right: 10px;
  &:hover {
    text-decoration: underline;
  }
}
::v-deep .el-upload-list.is-disabled {
  margin-top: -40px;
}
</style>
